package com.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.core.constants.Constants;
import com.common.core.domain.TableDataInfo;
import com.common.core.enums.ExamListType;
import com.common.core.enums.ResultCode;
import com.common.core.utils.ThreadLocalUtil;
import com.common.security.exception.ServiceException;
import com.common.security.service.TokenService;
import com.friend.domain.exam.Exam;
import com.friend.domain.exam.dto.ExamQueryDTO;
import com.friend.domain.exam.vo.ExamVO;
import com.friend.domain.user.UserExam;
import com.friend.domain.user.vo.UserVO;
import com.friend.manager.ExamCacheManager;
import com.friend.manager.UserCacheManager;
import com.friend.mapper.exam.ExamMapper;
import com.friend.mapper.user.UserExamMapper;
import com.friend.service.user.UserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RefreshScope
@Slf4j
public class UserExamImpl implements UserExamService {

    @Resource
    UserExamMapper userExamMapper;

    @Resource
    ExamMapper examMapper;

    @Resource
    ExamCacheManager examCacheManager;

    @Resource
    UserCacheManager userCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public int enter(String token, Long examId) {
        //首先检验报名条件是否符合
        log.info("examId:{}",examId);
        Exam exam = examMapper.selectById(examId);
        if(exam==null){
            //该竞赛不存在
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            //该竞赛已开始
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        //Long userId=tokenService.getUserId(token,secret);
        Long userId= ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if(userExam!=null){
            //该用户已报名
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }

        //先存数据库
        userExam=new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        int insert = userExamMapper.insert(userExam);
        //再存入缓存
        examCacheManager.addUserExamCache(userId,examId);
        return insert;
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //先从缓存中查看有没有
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        //先从redis中，读看看有几条数据
        Long total=examCacheManager.getListSize(examQueryDTO.getType(),userId);
        List<ExamVO> examVOList;
        if(total==null || total==0){
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            //说明redis中没有缓存数据
            examCacheManager.refreshCache(examQueryDTO.getType(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else{
            examVOList=examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if(CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }

        return TableDataInfo.success(examVOList,total);
    }
}
